import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

// 定义留言数据类型
interface MessageData {
  id: string;
  name: string;
  phone: string;
  email: string;
  content: string;
  timestamp: string;
}

// 定义存储文件路径
const MESSAGES_FILE = path.join(process.cwd(), 'data', 'messages.json');

// 确保数据目录存在
const ensureDataDirectoryExists = () => {
  const dataDir = path.join(process.cwd(), 'data');
  if (!fs.existsSync(dataDir)) {
    fs.mkdirSync(dataDir, { recursive: true });
  }
};

// 获取现有留言数据
const getExistingMessages = (): MessageData[] => {
  ensureDataDirectoryExists();
  try {
    if (!fs.existsSync(MESSAGES_FILE)) {
      return [];
    }
    const data = fs.readFileSync(MESSAGES_FILE, 'utf8');
    return JSON.parse(data) as MessageData[];
  } catch (error) {
    console.error('读取留言数据失败:', error);
    return [];
  }
};

// 保存留言数据
const saveMessages = (messages: MessageData[]): void => {
  ensureDataDirectoryExists();
  try {
    fs.writeFileSync(MESSAGES_FILE, JSON.stringify(messages, null, 2));
  } catch (error) {
    console.error('保存留言数据失败:', error);
    throw new Error('保存数据失败');
  }
};

// 处理POST请求
export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData();
    const name = formData.get('name') as string || '';
    const email = formData.get('email') as string || '';
    const content = formData.get('content') as string || '';
    const phone = formData.get('phone') as string || '';

    // 验证字段
    if (!name.trim() || !email.trim() || !content.trim() || !phone.trim()) {
      return NextResponse.json(
        { success: false, message: '请填写完整信息' },
        { status: 400 }
      );
    }

    // 邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email)) {
      return NextResponse.json(
        { success: false, message: '请输入有效的邮箱地址' },
        { status: 400 }
      );
    }

    // 手机号格式验证
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(phone)) {
      return NextResponse.json(
        { success: false, message: '请输入有效的手机号' },
        { status: 400 }
      );
    }

    // 创建新留言
    const newMessage: MessageData = {
      id: Date.now().toString(),
      name: name.trim(),
      phone: phone.trim(),
      email: email.trim(),
      content: content.trim(),
      timestamp: new Date().toISOString(),
    };

    // 获取现有留言并添加新留言
    const existingMessages = getExistingMessages();
    existingMessages.push(newMessage);

    // 保存更新后的留言列表
    saveMessages(existingMessages);

    return NextResponse.json({
      success: true,
      message: '提交成功',
    });
  } catch (error) {
    console.error('提交表单失败:', error);
    return NextResponse.json(
      { success: false, message: '提交失败，请重试' },
      { status: 500 }
    );
  }
}

// 处理GET请求，用于读取留言数据（可选）
export async function GET() {
  try {
    const messages = getExistingMessages();
    return NextResponse.json({
      success: true,
      data: messages,
    });
  } catch (error) {
    console.error('获取留言数据失败:', error);
    return NextResponse.json(
      { success: false, message: '获取数据失败' },
      { status: 500 }
    );
  }
}